package com.szrt.socket.ch02.tcp.demo01;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

public class T2 {
	
	
	/**
	 * 服务端
	 * @throws Exception
	 */
	@Test
	public void testName() throws Exception {
		
		//创建1个serversocket的对象
		ServerSocket ss=new ServerSocket(9999);
		System.out.println("服务端启动");
		
		//监听连接
		Socket socket = ss.accept();
		System.out.println("开始接受客户端的信息");
		System.out.println(ss.getInetAddress().getHostAddress());
		
		//得到输入流
		InputStream is = socket.getInputStream();
		System.out.println(is.getClass());
		
		//把输入流的信息打印到控制台
		byte[] b=new byte[10];
		int len=0;
		while((len=is.read(b))!=-1){
			String name = new String(b,0,len);
			System.out.print(name);
		}
		is.close();
		socket.close();
		ss.close();
		
	}
	
	/**
	 * 客户端
	 * @throws Exception
	 */
	@Test
	public void client() throws Exception {
		
		//创建一个socket的对象链接
		Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
		
		//得到输入流
		OutputStream os = socket.getOutputStream();
		
		//调用write方法并以流的形式往服务端发送数据
		os.write("好好学习，争取被录取".getBytes());
		os.close();
		socket.close();
		
		
	}

}
